import re
from apps.verifications.libs.captcha.captcha import captcha
from django.conf import settings
from django.shortcuts import render, redirect
from django.views import View
from django_redis import get_redis_connection

from apps.verifications.constants import VERIFY_EMAIL_TOKEN_EXPIRES
from utils.response_code import RETCODE
from django.contrib.auth import login, logout
from django import http
import random
from django.core.mail import send_mail
from apps.users.models import User
# Create your views here.
class emailCodeView(View):
    def get(self,request,email):
        '''
        :param request:
        :param email: 邮箱号
        :return:
        '''
        #连接redis数据库
        redis_conn = get_redis_connection('verify_code')
        #判断是否频繁发送邮箱
        send_flag=redis_conn.get('send_flag_%s'%email)
        if send_flag:
            return http.JsonResponse({'code':RETCODE.THROTTLINGERR,'errmsg':'发送验证码过于频繁'})
        #生成6位验证码
        email_code = '%06d' % random.randint(0, 999999)
        #测试
        #email_code='1234'
        redis_conn.setex('send_flag_%s'%email,60,1)
        redis_conn.setex('email_%s'%email,300,email_code)
        subject='JobFind邮箱验证'
        html_message=f'''
        <p>尊敬的用户您好！</p>
        <p>感谢使用JobFind。</p>
        <p>您的验证码为：{email_code}</p>
        '''
        #发邮件
        print(f'发送成功，验证码为{email_code}')
        send_mail(subject,'',from_email=settings.EMAIL_FROM,recipient_list=[f'{email}'],html_message=html_message)
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok'})
class ImageCodeView(View):
    def get(self,request,uuid):
        '''
        图形验证码
        :param request:
        :param uuid: 通用唯一识别符
        :return: image/jpg
        '''
        text,image=captcha.generate_captcha()
        #保存到缓存里
        redis_conn=get_redis_connection('verify_code')
        redis_conn.setex("image_%s"%uuid,300,text)
        #返回结果
        return http.HttpResponse(image,content_type='image/png')













